# -*- coding: utf8 -*-

import urllib2
import socket
from django.utils import simplejson
from puppy.model import Query, Response, Item
from puppy.service.Config import *

def search(query):
  """Search function for Google AJAX Search.
  
  Parameters:
  
  * query (puppy.model.OpenSearch.Query)
  
  Returns:
  
  * puppy.model.OpenSearch.Response
  
  Raises:
  
  * urllib2.URLError
  
  """
  
  def parse_google_json(site, url, query, num_results, results):
    """Create a OpenSearch Response from Google AJAX Search results.
    
    Google's search API returns results in JSON format. This function simply loads the JSON into memory and creates an equivalent representation that is OpenSearch compliant.
    
    Parameters:
    
    * site (str): search engine name
    * url (str): search url used
    * query (str): query search terms (n.b. not a OpenSearch Query object)
    * num_results (int): number of desired results
    * results (dict): results from service
    
    Returns:
    
    * OpenSearch.Response
    
    """
    response = Response()
    response.title = "{0}: {1}".format(site, query)
    response.link = results['cursor']['moreResultsUrl']
    response.description = "Search results for '{0}' at {1}".format(query, site)
    response.total_results = results['cursor']['estimatedResultCount']
    response.start_index = results['cursor']['currentPageIndex']
    response.items_per_page = num_results
    response.query = query
    for result in results['results']:
      item = Item()
      item.title = result['title']
      item.link = result['url']
      item.description = result['content']
      response.items.append(item)
    return response
  
  
  # api_key = 'ABQIAAAAFAoRzdMk5GDWWqERtyk_xBSEXOG7OzWGHB9nvn0oqrrXOYaOtxQ1xHwuPCKlQz3Zpl-bh6pexTnf2g'
  ip_addr = socket.gethostbyname(socket.gethostname())
  num_results = 8 # oddly, the maximum the api supports
  url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={0}&key={1}&userip={2}&rsz={3}".format(urllib2.quote(query.search_terms), GOOGLE_API_KEY, ip_addr, num_results)
  # url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q={0}".format(query)
  
  try:
    request = urllib2.Request(url, None, {'Referer': "http://www.dcs.gla.ac.uk/~rjg/"})
    response = urllib2.urlopen(request)  
    results = simplejson.load(response)
    return parse_google_json('Google', url, query.search_terms, num_results, results['responseData'])
  except urllib2.URLError, e:
    print "Error in SearchService: Google AJAX Search failed"
